package com.reservation.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义TypeHandler用于将数据库中的逗号分隔字符串转换为List<String>
 */
@MappedTypes(List.class)
public class StringToListTypeHandler extends BaseTypeHandler<List<String>> {

    private static final String DELIMITER = ",";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        // 将List转换为逗号分隔的字符串存储到数据库
        String value = String.join(DELIMITER, parameter);
        ps.setString(i, value);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return convertToList(rs.getString(columnName));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return convertToList(rs.getString(columnIndex));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return convertToList(cs.getString(columnIndex));
    }    /**
     * 将JSON数组格式的字符串转换为List<String>
     */
    private List<String> convertToList(String value) {
        if (value == null || value.isEmpty()) {
            return Collections.emptyList();
        }
        
        // 处理JSON数组格式的字符串，如: ["投影仪","音响系统","无线网络"]
        if (value.startsWith("[") && value.endsWith("]")) {
            // 移除前后的方括号
            String content = value.substring(1, value.length() - 1);
            
            // 如果是空数组，直接返回空列表
            if (content.trim().isEmpty()) {
                return Collections.emptyList();
            }
            
            // 将内容按逗号分隔，并处理每个元素
            return Arrays.stream(content.split(","))
                    .map(s -> s.trim().replace("\"", "")) // 移除引号
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());
        } 
        // 处理普通的逗号分隔字符串
        else {
            return Arrays.stream(value.split(DELIMITER))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.toList());
        }
    }
}
